import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import{Hero } from './Hrtest.module';

//引入service 服务
import { HeroServiceProvider } from '../../providers/hero-service/hero-service';
import { OnInit } from '@angular/core'; //ON init
/**
 * Generated class for the HerosPage page.
 *
 * See http://ionicframework.com/docs/components/#navigation for more info
 * on Ionic pages and navigation.
 */
//const   不要放在controctor 里面
const HEROES: Hero[] = [
  { id: 11, name: 'Mr. Nice' },
  { id: 12, name: 'Narco' },
  { id: 13, name: 'Bombasto' },
  { id: 14, name: 'Celeritas' },
  { id: 15, name: 'Magneta' },
  { id: 16, name: 'RubberMan' },
  { id: 17, name: 'Dynama' },
  { id: 18, name: 'Dr IQ' },
  { id: 19, name: 'Magma' },
  { id: 20, name: 'Tornado' }
];


@IonicPage()
@Component({
  selector: 'page-heros',
  templateUrl: 'heros.html',
})
export class HerosPage implements OnInit{
// 接受页面参数：这个参数应该是可以被DeepLinker序列化的，因此建议设置为一个string或number。
ngOnInit(): void {
   this.getHeroes();
  }

  title = 'Tour of Heroes';
  hero = 'Windstorm';
  constructor(public navCtrl: NavController, public navParams: NavParams,private heroService: HeroServiceProvider) {
    
   
  }
  ionViewDidLoad() {
    console.log('ionViewDidLoad HerosPage');
  }

  heroes = HEROES;
 testSevice:Hero[];
       
   //引入外部的Hero
   hero1: Hero = {
  id: 2,
  name: 'Windstorm obj obj'
};

// 点击事件
selectedHero:Hero;
onSelected(hero: Hero):void{

   this.selectedHero = hero;
   console.log(this.selectedHero.name);
}




// service
 getHeroes(): void {
    // this.testSevice = this.heroService.getHeroes();
    // console.log(this.testSevice);
    this.heroService.getHeroesSlowly().then(heroes111 => this.testSevice = heroes111);
    // 执行了一个hero Service层中的getHeroes方法 返回的值是heros....返回给这里的testService
  }


  // 保存英雄数据

  save(): void {
  this.heroService.update(this.hero1)
    // .then(() => this.goBack());
}



// add heroes

add(name: string): void {
  name = name.trim();
  if (!name) { 
    
    // 请输入列表  封装toast 方法
    return; }
  this.heroService.create(name)
    .then(hero => {
      this.heroes.push(hero);  //渲染heroes列表
      this.selectedHero = null;
    });
}


delete(hero:Hero){
  console.log(typeof(hero.id));
this.heroService
      .delete(hero.id)
      .then(() => {
        this.heroes = this.heroes.filter(h => h !== hero);  //这种删除没有重新渲染dom 只是在filter里去掉了hero....
        // 如果这个英雄选中了,那么选中的就没了被删除了
        if (this.selectedHero === hero) { this.selectedHero = null; }
      });
}

}







